package com.example.service;

import com.example.model.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户服务类
 * 
 * @author demo
 * @since 1.0.0
 */
@Service
public class UserService {
    
    private final AtomicLong idGenerator = new AtomicLong(1);
    private final List<User> users = new ArrayList<>();
    
    public UserService() {
        // 初始化一些测试数据
        users.add(new User(idGenerator.getAndIncrement(), "admin", "admin@example.com"));
        users.add(new User(idGenerator.getAndIncrement(), "user1", "user1@example.com"));
        users.add(new User(idGenerator.getAndIncrement(), "user2", "user2@example.com"));
    }
    
    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return new ArrayList<>(users);
    }
    
    /**
     * 根据ID获取用户
     */
    public User getUserById(Long id) {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
    
    /**
     * 创建新用户
     */
    public User createUser(String username, String email) {
        User user = new User(idGenerator.getAndIncrement(), username, email);
        users.add(user);
        return user;
    }
    
    /**
     * 更新用户信息
     */
    public User updateUser(Long id, String username, String email) {
        User user = getUserById(id);
        if (user != null) {
            user.setUsername(username);
            user.setEmail(email);
            user.setUpdateTime(java.time.LocalDateTime.now());
        }
        return user;
    }
    
    /**
     * 删除用户
     */
    public boolean deleteUser(Long id) {
        return users.removeIf(user -> user.getId().equals(id));
    }
} 